package com.toman;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.annotation.NonNull;
import android.support.multidex.MultiDex;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tencent.smtt.sdk.QbSdk;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.DeviceHouseDayPlanEntity;
import com.toman.JavaBean.DeviceHouseMonthPlanEntity;
import com.toman.JavaBean.MessageDataBean;
import com.toman.JavaBean.SysUserEntity;
import com.toman.Util.IntentUtils;
import com.toman.Util.PicassoImageLoader;
import com.toman.Util.SPUtils;
import com.toman.Util.StringUtils;
import com.toman.Util.ToastUtil;
import com.toman.ui.menu.MenuJump;
import com.toman.ui.msg.MsgActivity;
import com.toman.ui.work.choose.ChooseRemindListEmptyActivity;
import com.toman.ui.work.device.CompleteEquipmentActivity;
import com.toman.ui.work.device.DeviceRepairActivity;
import com.toman.ui.work.device.PreHot2Activity;
import com.toman.ui.work.device.PreMaintenanceActivity;
import com.toman.ui.work.device.PreviewHotActivity;
import com.toman.ui.work.device.TallyActivity;
import com.toman.ui.work.management.ProblemFeedbackActivity;
import com.toman.ui.work.workplan.WorkshopDayPlanActivity;
import com.toman.ui.work.workplan.WorkshopMonthPlanActivity;
import com.toman.ui.work.workplan.WorkshopSubmitActivity;
import com.toman.ui.work.workshop.CenterTableActivity;
import com.toman.ui.work.workshop.DispatchingActivity;
import com.toman.ui.work.workshop.GetActivity;
import com.toman.ui.work.workshop.NoPlanSubmitActivity;
import com.toman.ui.work.workshop.PlanActivity;
import com.toman.ui.work.workshop.SubmitActivity;
import com.toman.widget.BadgeUtil;
import com.toman.widget.callback.EmptyCallback;
import com.toman.widget.callback.ErrorCallback;
import com.toman.widget.callback.LoadingCallback;
import com.toman.widget.callback.WifiCallback;
import com.kingja.loadsir.core.LoadSir;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.view.CropImageView;
import com.lzy.okhttputils.OkHttpUtils;
import com.toman.ColorView.MyPreference;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.ywanhzy.demo.AppContext;

import org.android.agoo.intent.IntentUtil;

import java.util.ArrayList;
import java.util.List;

import lombok.Data;
import lombok.EqualsAndHashCode;

import static com.toman.ui.HomeActivity.REQUEST_CODE_CAMERA;
import static com.toman.ui.HomeActivity.REQUEST_CODE_PERMISSION;
import static com.toman.ui.HomeActivity.REQUEST_CODE_PHONE;


/**
 * 应用Application类
 */
@Data
@EqualsAndHashCode(callSuper = false)
public class MyApplication extends AppContext {

    private ImagePicker imagePicker;
    private static MyApplication mContext;
    private SysUserEntity bean;
    //保存登录token
    private SharedPreferences sp;
    public static MyPreference mPreference;
    public PushAgent mPushAgent;

    // 单例模式中获取唯一的ExitApplication 实例
    public static MyApplication getInstance() {
        return mContext;
    }

    public Handler msgHandler;
    //忘记密码pop弹窗保存数据
    String mobile = "";
    String sms = "";
    String newpwd = "";
    String confirmpwd = "";
    String token;
    String userId;
    String mCompanyId;
    String username;
    String departmentId;
    public int count = 0;

    public Handler getMsgHandler() {
        return msgHandler;
    }

    public void setMsgHandler(Handler msgHandler) {
        this.msgHandler = msgHandler;
    }

    int type = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
//initPermmison();
        OkHttpUtils.init(this);
        //以下都不是必须的，根据需要自行选择
        OkHttpUtils.getInstance()//
//                .debug("OkHttpUtils")                                              //是否打开调试
                .setConnectTimeout(5000)               //全局的连接超时时间
                .setReadTimeOut(OkHttpUtils.DEFAULT_MILLISECONDS);                  //全局的读取超时时间
//                .setWriteTimeOut(OkHttpUtils.DEFAULT_MILLISECONDS)                 //全局的写入超时时间
        //.setCookieStore(new MemoryCookieStore())                           //cookie使用内存缓存（app退出后，cookie消失）
        //.setCookieStore(new PersistentCookieStore())                       //cookie持久化存储，如果cookie不过期，则一直有效
//                .addCommonHeaders(headers)                                         //设置全局公共头
//                .addCommonParams(params);                                          //设置全局公共参数

//        headers.put("contentType", "application/json");
//        headers.put("Content-Type", "application/json");
//
        OkHttpUtils.getInstance()
                .debug("OkHttpUtils");
//
//                //是否打开调试
//                .addCommonHeaders(headers);                    //设置全局公共头
        LoadSir.beginBuilder()
                .addCallback(new ErrorCallback())//'添加各种状态页
                .addCallback(new EmptyCallback())
                .addCallback(new LoadingCallback())
                .addCallback(new WifiCallback())

//                .addCallback(new TimeoutCallback())
//                .addCallback(new CustomCallback())
                .setDefaultCallback(LoadingCallback.class)//设置默认状态页
                .commit();


//        QbSdk.initX5Environment(this, new QbSdk.PreInitCallback() {
//            @Override
//            public void onCoreInitFinished() {
//                //x5内核初始化完成回调接口，此接口回调并表示已经加载起来了x5，有可能特殊情况下x5内核加载失败，切换到系统内核。
//
//            }
//
//            @Override
//            public void onViewInitFinished(boolean b) {
//                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
//                Log.e("@@", "加载内核是否成功:" + b);
//            }
//        });

        mPreference = new MyPreference(getApplicationContext());
        sp = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        UMConfigure.init(this, "5b616d108f4a9d3c13000300", "android", UMConfigure.DEVICE_TYPE_PHONE, "128f6b1962966a27ad4a04f8fc6ca3b2");
//        UMConfigure.setLogEnabled(true);
        MobclickAgent.setSecret(this, "ffj0gaanfmxrdopiwtqtxte2drtynp17");
        mPushAgent = PushAgent.getInstance(this);
//注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                ToastUtil.print("device: " + deviceToken);
                SPUtils.put(getApplicationContext(), "deviceToken", deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
                ToastUtil.print("注册失败" + s);
            }
        });
        mPushAgent.setMessageHandler(messageHandler);
//        MobclickAgent.setDebugMode( true );
        mPushAgent.setDisplayNotificationNumber(5);
        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SERVER); //声音
        mPushAgent.setNotificationPlayLights(MsgConstant.NOTIFICATION_PLAY_SERVER);//呼吸灯
        mPushAgent.setNotificationPlayVibrate(MsgConstant.NOTIFICATION_PLAY_SERVER);//振动
        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
//                Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
                ToastUtil.print("通知栏消息：" + msg.custom);
                MessageDataBean bean = (MessageDataBean) JSON.parseObject(msg.custom, MessageDataBean.class);
                dealMsg(bean);
//                MenuJump.dealMsg(this, bean);

//                Intent intent=new Intent(getApplicationContext(),TallyActivity.class);
//                intent.addFlags(Intent .FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);
            }
        };
        mPushAgent.setNotificationClickHandler(notificationClickHandler);
        //选择相册图片
        imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PicassoImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(9);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }
    }


    UmengMessageHandler messageHandler = new UmengMessageHandler() {
        @Override
        public void dealWithCustomMessage(final Context context, final UMessage msg) {
            new Handler(getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    // 对于自定义消息，PushSDK默认只统计送达。若开发者需要统计点击和忽略，则需手动调用统计方法。
                    ToastUtil.print("自定义消息：" + msg.custom);
                    BadgeUtil.setBadgeCount(getApplicationContext(), ++count, R.mipmap.baselogo);
                    boolean isClickOrDismissed = true;
                    if (isClickOrDismissed) {
                        //自定义消息的点击统计
                        UTrack.getInstance(getApplicationContext()).trackMsgClick(msg);
                    } else {
                        //自定义消息的忽略统计
                        UTrack.getInstance(getApplicationContext()).trackMsgDismissed(msg);
                    }
                    if (msgHandler != null) {
                        Message msg = msgHandler.obtainMessage(1);
                        msgHandler.sendMessage(msg);
                    }
//                    Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
                }
            });
        }
    };

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getSms() {
        return sms;
    }

    public void setSms(String sms) {
        this.sms = sms;
    }

    public String getNewpwd() {
        return newpwd;
    }

    public void setNewpwd(String newpwd) {
        this.newpwd = newpwd;
    }

    public String getConfirmpwd() {
        return confirmpwd;
    }

    public void setConfirmpwd(String confirmpwd) {
        this.confirmpwd = confirmpwd;
    }

    public ImagePicker getImagePicker() {
        return imagePicker;
    }

    public SharedPreferences getSp() {
        return sp;
    }

    public void setSp(SharedPreferences sp) {
        this.sp = sp;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public SysUserEntity getBean() {
        return bean;
    }

    public void setBean(SysUserEntity bean) {
        this.bean = bean;
    }

    //通知栏消息
    public void dealMsg(MessageDataBean bean) {
        Bundle bundle = new Bundle();
        bundle.putString("status", bean.getOperateType());
        bundle.putString("etSearch", bean.getRecordId() + "");
        if (StringUtils.isNotEmpty(bean.getTabIndex())) {
            bundle.putString("status", bean.getTabIndex());
        }
        Intent intent = new Intent();
        switch (bean.getType()) {
            case "1":
                intent = new Intent(getApplicationContext(), TallyActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                break;

            case "2":
                intent = new Intent(getApplicationContext(), CompleteEquipmentActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                break;
            case "3":
                intent = new Intent(getApplicationContext(), PreMaintenanceActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                break;
            case "4":
                intent = new Intent(getApplicationContext(), DeviceRepairActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ;
                break;

            case "6":
                intent = new Intent(getApplicationContext(), PlanActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ;
                break;
            case "7":
                intent = new Intent(getApplicationContext(), DispatchingActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ;
                break;
            case "8":
                intent = new Intent(getApplicationContext(), GetActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ;
                break;
            case "9":
                intent = new Intent(getApplicationContext(), SubmitActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                bundle.putString("isfirstReport", bean.getExtra());
                break;
            case "12":
                intent = new Intent(getApplicationContext(), ProblemFeedbackActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                break;
            case "13":
                intent = new Intent(getApplicationContext(), ChooseRemindListEmptyActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                break;
            case "14":
                intent = new Intent(getApplicationContext(), NoPlanSubmitActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                break;
            case "15":
                intent = new Intent(getApplicationContext(), WorkshopMonthPlanActivity.class);
                JSONObject jsonObject= (JSONObject) bean.getExtraMap().get("entity");
                bundle.putSerializable("entity", (DeviceHouseMonthPlanEntity)JSONObject.parseObject(jsonObject.toJSONString(),DeviceHouseMonthPlanEntity.class));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                break;
            case "16":
                jsonObject= (JSONObject) bean.getExtraMap().get("entity");
                bundle.putSerializable("entity", (DeviceHouseDayPlanEntity)JSONObject.parseObject(jsonObject.toJSONString(),DeviceHouseDayPlanEntity.class));
                intent = new Intent(getApplicationContext(), WorkshopDayPlanActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                break;
            case "17":
                intent = new Intent(getApplicationContext(), WorkshopSubmitActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                break;
            case "18":
                intent = new Intent(getApplicationContext(), PreviewHotActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                break;
            case "19":
                intent = new Intent(getApplicationContext(), CenterTableActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                break;
        }
        if (bean.getDealStatus() == 0) {
            List<MessageDataBean> dataBeans = new ArrayList<>();
            bean.setClearType("4");
            dataBeans.add(bean);
            MsgActivity.clickEvent(this, NewBaseUrl.getNotifyClear, dataBeans, (String) SPUtils.get(this, "token", ""), "清空消息", null);
        }
        intent.putExtras(bundle);

        startActivity(intent);


    }


}
